package com.renli.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.renli.exception.RenLiException;
import com.renli.mapper.WorkDayMapper;
import com.renli.model.domain.Punishment;
import com.renli.model.domain.Staff;
import com.renli.model.domain.StaffWages;
import com.renli.model.domain.WorkDay;
import com.renli.model.dto.UpdateDayDto;
import com.renli.result.R;
import com.renli.service.PunishmentService;
import com.renli.service.StaffService;
import com.renli.service.StaffWagesService;
import com.renli.service.WorkDayService;
import com.renli.utils.Date;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
public class WorkDayServiceImpl extends ServiceImpl<WorkDayMapper, WorkDay> implements WorkDayService {
    @Autowired
    private PunishmentService punishmentService;
    @Autowired
    private StaffWagesService staffWagesService;
    @Autowired
    private StaffService staffService;
    @Override
    public R updateAll(UpdateDayDto updateDayDto, String s) {
        Long id = updateDayDto.getStaffId();
//        if (id==null){
//            throw new RenLiException("员工工号为空");
//        }
        //更新staffWages工资
        updateStaffWages(updateDayDto, id,s);
        //更新workDay
        updateWorkday(updateDayDto, id);

        //新增punishment表
        updatePunishment(updateDayDto, id,s);
        return new R(1,"修改成功");
    }

    private void updatePunishment(UpdateDayDto updateDayDto, Long id,String s) {
        Punishment punishment=new Punishment();
        punishment.setStaffId(id);
        LambdaQueryWrapper<Staff> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Staff::getId,id);
        Staff staff = staffService.getOne(queryWrapper);
        if (staff==null){
            throw new RenLiException("punishment在staff表中查无次信息");
        }
        String name = staff.getName();
        punishment.setReward(updateDayDto.getReward());
        punishment.setPenalty(updateDayDto.getPenalty());
        punishment.setCause(updateDayDto.getCause());
        punishment.setProcessing_time(LocalDateTime.now());
        punishment.setAccountProcessor(s);

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime time = LocalDateTime.now();
        String localTime = df.format(time);
        String description=null;
        if (updateDayDto.getReward()!=0){
            description= s+"奖励了"+name+updateDayDto.getReward()+"元，理由:"
                +updateDayDto.getCause()+"。"+localTime;}
        else {
            description=s+"罚款"+name+updateDayDto.getPenalty()+"元，理由："
                    +updateDayDto.getCause()+"。时间："+localTime;
        }
        punishment.setDescription(description);
        punishment.setName(name);
        boolean save = punishmentService.save(punishment);
        if (!save){
            throw new RenLiException("新增punishment表失败");
        }
    }

    private void updateWorkday(UpdateDayDto updateDayDto, Long id) {
        Integer dayLate = updateDayDto.getDayLate();
        Integer daysLost = updateDayDto.getDaysLost();
        Integer workOvertime = updateDayDto.getWorkOvertime();
        LambdaQueryWrapper<WorkDay> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkDay::getStaffId,id);
        WorkDay workDay = this.getOne(queryWrapper);
        if (workDay==null){
            throw new RenLiException("在workDay表查无此信息");
        }
        workDay.setDayLate(dayLate);
        workDay.setDaysLost(daysLost);
        workDay.setWorkOvertime(workOvertime);
        if (daysLost==0){
            workDay.setFullAttendance(1);
        }
        if (daysLost>0){
            workDay.setFullAttendance(0);
        }
        boolean b = this.updateById(workDay);
        if (!b){
            throw new RenLiException("更新workDay工资失败");
        }
    }

    private void updateStaffWages(UpdateDayDto updateDayDto, Long id,String s) {
        Integer dayLate = updateDayDto.getDayLate();
        Integer daysLost = updateDayDto.getDaysLost();
        Integer workOvertime = updateDayDto.getWorkOvertime();
        Double basicWage = updateDayDto.getBasicWage();
        Double postPay = updateDayDto.getPostPay();
        LambdaQueryWrapper<StaffWages> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(StaffWages::getStaffId, id);
        StaffWages staffWages = staffWagesService.getOne(queryWrapper);
        if (staffWages==null){
            throw new RenLiException("在staffWages表查无此信息");
        }
        if (updateDayDto.getDaysLost()>0){
            staffWages.setFullAttendenceAward((double) 0);
        }
        if (updateDayDto.getDaysLost()==0){
            staffWages.setFullAttendenceAward(300.0);
        }
        staffWages.setPostPay(postPay);
        staffWages.setBasicWage(basicWage);
        //岗位工资=岗位每天工资*（当月天数-缺勤天数）
        Double plus1 = postPay * (Date.getCurrentMonthLastDay()-daysLost);
        staffWages.setPostPayAll(plus1);

        //加班工资=加班时长*加班一次的钱
        Double plus2= staffWages.getOvertimePay()*workOvertime;
        staffWages.setOvertimePayAll(plus2);

        //缺勤罚款=当月缺勤次数*缺勤一次罚款
        Double delete1 = staffWages.getLatePay()*daysLost;
        staffWages.setLatePayAll(delete1);

        //迟到罚款=当月迟到次数*迟到一次罚款
        Double delete2 = staffWages.getDateLate()*dayLate;
        staffWages.setDateLateAll(delete2);

        //计算总金额=基础工资+岗位工资+全勤奖+加班工资-缺勤罚款-迟到罚款+奖金-罚款
       Double all= plus1+plus2+staffWages.getFullAttendenceAward()
               +basicWage-delete1-delete2+updateDayDto.getReward()-updateDayDto.getPenalty();

       //将总金额放进去
       staffWages.setThisMonthsSalary(all);
       staffWages.setUpdatePeople(s);
       staffWages.setUpdateTime(LocalDateTime.now());

        boolean b = staffWagesService.updateById(staffWages);
        if (!b){
            throw new RenLiException("更新StaffWages工资失败");
        }
    }
}
